package com.wind.cloud.common.config.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 打印日志
 * <br>
 * 依赖BufferingClientHttpRequestFactory
 *
 * @author wind.
 * @see BufferingClientHttpRequestFactory
 */
public class LoggingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    private final String CHARSET_NAME = "UTF-8";

    private final static Logger log = LoggerFactory.getLogger(LoggingClientHttpRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
        if (log.isInfoEnabled()) {
            log.info("URI:{}, Method:{}, Headers:{}", request.getURI(), request.getMethod(), request.getHeaders());
            log.info("Request body:{}", new String(body, CHARSET_NAME));
        }
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        if (log.isInfoEnabled()) {
            StringBuilder inputStringBuilder = new StringBuilder(250);
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), CHARSET_NAME))) {
                String line = bufferedReader.readLine();
                while (line != null) {
                    inputStringBuilder.append(line);
                    inputStringBuilder.append('\n');
                    line = bufferedReader.readLine();
                }
            }
            log.info("Status code:{}, Status text:{}, Headers:{}", response.getStatusCode(), response.getStatusText(), response.getHeaders());
            log.info("Response body:{}", inputStringBuilder.toString());
        }
    }

}
